<template>
  <el-button type="primary" @click="dialogVisible = true">新增bug</el-button>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column :label="t('developer.addbug')">
        <template #default="scope">
          {{ scope.row.reason }}
        </template>
      </el-table-column>
    <el-table-column label="项目名">
      <template #default="scope">
        {{ scope.row.projectname }}
      </template>
    </el-table-column>

    <el-table-column label="分配人">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span style="margin-left: 10px">{{ scope.row.username }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="bug新增理由">
      <template #default="scope">
        {{ scope.row.reason }}
      </template>
    </el-table-column>

    <el-table-column label="类别">
      <template #default="scope">
        {{ scope.row.bugType == 1 ? '功能' : scope.row.bugType == 2 ? '样式' : '结构' }}
      </template>
    </el-table-column>

    <el-table-column label="开始时间">
      <template #default="scope">
        {{ dayjs(scope.row.start).format('YYYY年MM月DD日 HH:mm:ss') }}
      </template>
    </el-table-column>
    <el-table-column label="结束时间">
      <template #default="scope">
        {{ scope.row.end ? dayjs(scope.row.end).format('YYYY年MM月DD日 HH:mm:ss') : '' }}
      </template>
    </el-table-column>
    <el-table-column label="状态">
      <template #default="scope">
        {{ scope.row.type == 1 ? '待处理' : scope.row.type == 2 ? '处理中' : '已处理' }}
      </template>
    </el-table-column>

    <el-table-column label="附件">
      <template #default="scope">
        <el-image
          v-if="scope.row.extend"
          style="width: 100px; height: 100px"
          :src="'/api/' + scope.row.extend.split(',')[0]"
          :zoom-rate="1.2"
          :max-scale="7"
          :min-scale="0.2"
          preview-teleported="true"
          :preview-src-list="
            scope.row.extend.split(',').map((item: any) => {
              return '/api/' + item
            })
          "
          :initial-index="4"
          fit="cover"
        />
      </template>
    </el-table-column>

    <el-table-column label="操作">
      <template #default="scope">
        <div v-if="scope.row.type != 3">
          <el-button size="small" type="danger" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button size="small" @click="update(scope.row, 3)">完成</el-button>
        </div>
        <div v-if="scope.row.type == 3">
          <el-button type="success" @click="ElMessage('bug已完结,无法操作')">已完结</el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="dialogVisible" title="新增bug" width="30%">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="项目名" prop="project">
        <el-select v-model="ruleForm.project" placeholder="请选择项目名">
          <el-option
            v-for="item in options3"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="bug新增理由" prop="reason">
        <el-input v-model="ruleForm.reason" />
      </el-form-item>
      <el-form-item label="bug类别" prop="bugType">
        <el-select v-model="ruleForm.bugType" placeholder="请选择bug类别">
          <el-option
            v-for="item in options2"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="开始时间" prop="start">
        <el-date-picker v-model="ruleForm.start" type="datetime" placeholder="请选择开始时间" />
      </el-form-item>

      <el-form-item label="分配人" prop="getdevelop">
        <el-select v-model="ruleForm.getdevelop" placeholder="请选择开发人员">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="bug附件" prop="extend">
        <el-upload
          ref="uploadRef"
          name="filename"
          v-model:file-list="fileList"
          class="upload-demo"
          action="/api/uploads"
          multiple
          :limit="3"
          :auto-upload="false"
          :on-success="success"
        >
          <el-button type="primary">点击选择附件</el-button>
          <template #tip>
            <div class="el-upload__tip">文件大小不能超过 500KB</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">新增</el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <br />
  <!-- 分页 -->
  <div class="demo-pagination-block">
    <el-pagination
      @change="change"
      v-model:current-page="pageindex"
      v-model:page-size="pageNum"
      background
      layout="prev, pager, next"
      :total="total"
    />
  </div>

  <el-dialog v-model="editDialogVisible" title="编辑bug" width="30%">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="bug归属">
        <el-select v-model="Editposts" :placeholder="tipType">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="bug描述" prop="textarea2">
        <el-input
          v-model="textarea2"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea"
          placeholder="Please input"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { developerQuery, developerAdd, developersUpdate } from '../services/developerService'
import type { FormInstance, FormRules, UploadInstance } from 'element-plus'
import { userQuery } from '../services/userService'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { useI18n } from "vue-i18n"; 
const { t } = useI18n()

interface Developer {
  project: String
  _id?: string
  username: string
  reason: string
  start: string
  end: string
  extend: string
  bugType: string
  type: number
}
let dialogVisible = ref<boolean>(false) //控制显示
const ruleFormRef = ref<FormInstance>() //表单元素
const tableData = ref<Array<Developer>>([])
const ruleForm = reactive({
  //数据
  reason: '',
  start: '',
  end: '',
  bugType: '',
  extend: '',
  getdevelop: '',
  project: ''
})
// 新增分配人
let options = ref<any>([])
// bug类别
let options2 = ref<any>([])

// 项目名
let options3 = ref<any>([])

// 分页
let pageindex = ref(1) //显示第几页
let pageNum = ref(5) //每页显示数据
let total = ref() //数据总数

const change = (val1: number, val2: number) => {
  pageindex.value = val1
  search()
}

// 编辑
let editDialogVisible = ref<boolean>(false)
let tipType: any = ref('')
let Editposts: any = ref('')
let EditId: any = ref('')
let textarea2: any = ref('')
// let developId:any = ref('')

let fileList = ref<any>([]) //文件集合
let fileSuccessList = ref<any>([]) //上传成功文件的集合
const uploadRef = ref<UploadInstance>() //组件名称

const rules = reactive<FormRules<typeof ruleForm>>({
  //规格
  reason: [{ required: true, message: 'bug理由不能为空', trigger: 'blur' }],
  start: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  bugType: [{ required: true, message: 'bug类别不能为空', trigger: 'blur' }],
  getdevelop: [{ required: true, message: '开发人员不能为空', trigger: 'blur' }],
  project: [{ required: true, message: '项目名不能为空', trigger: 'blur' }]
})

onMounted(async () => {
  search()
})

let search = async () => {
  let res = await developerQuery({ pageindex: pageindex.value, pageNum: pageNum.value })
  tableData.value = res.data.data

  total.value = res.data.total

  // 新增岗位类目
  let res2 = await userQuery({ type: [2] })
  options.value = res2.data.data.map((item: any) => {
    return { label: item.username, value: item._id }
  })

  // bug类别列表
  options2.value = res.data.bugTypeList?.map((item: any) => {
    return { label: item.name, value: item._id }
  })

  // 项目列表
  options3.value = res.data.projectList.map((item: any) => {
    return { label: item.project, value: item._id }
  })
}

let success = async (res: any) => {
  if (res.code == 200) {
    fileSuccessList.value.push(res.url)
    if (fileSuccessList.value.length == fileList.value.length) {
      let params = {
        reason: ruleForm.reason,
        start: ruleForm.start,
        bugtypeid: ruleForm.bugType,
        userid: ruleForm.getdevelop,
        projectid: ruleForm.project,
        extend: fileSuccessList.value.join(',')
      }
      let res = await developerAdd(params)
      if (res.data.code == 200) {
        ElMessage(res.data.msg)
        tableData.value.unshift(res.data.data[0]) //数据同步到列表
        ruleFormRef.value?.resetFields() //清空
        fileList.value = []
        fileSuccessList.value = []
        dialogVisible.value = false //隐藏
      } else {
        ElMessage(res.data.msg)
      }
    }
  }
}

//编辑事件
const handleEdit = (index: number, row: Developer) => {
  editDialogVisible.value = true
  EditId.value = row._id
  textarea2.value = row.reason
  tipType.value = row.username
  
}

// ok
let update = async (item: any, type: any) => {
  let end = new Date()
  let res = await developersUpdate({ _id: item._id, type, end })

  if (res.data.code == 200) {
    ElMessage(res.data.msg)
    item.type = type
    item.end = end
  } else {
    ElMessage(res.data.msg)
  }
}

//提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      if (!editDialogVisible.value) {
        // 添加
        if (fileList.value.length) {
          //表示选了附件
          uploadRef.value!.submit() //上传
        } else {
          let params = {
            reason: ruleForm.reason,
            start: ruleForm.start,
            projectid: ruleForm.project,
            bugtypeid: ruleForm.bugType,
            userid: ruleForm.getdevelop
          }
          let res = await developerAdd(params)
          if (res.data.code == 200) {
            ElMessage(res.data.msg)
            tableData.value.unshift(res.data.data[0])
            formEl.resetFields()
            dialogVisible.value = false
          } else {
            ElMessage(res.data.msg)
          }
        }
      } else {
        // 更新
        let res = await developersUpdate({ _id:EditId.value,reason: textarea2.value,userid: Editposts.value})

        if (res.data.code == 200) {
          ElMessage(res.data.msg)
          formEl.resetFields()
          editDialogVisible.value = false
          Editposts.value = ''
          // 同步
          tableData.value.forEach((item:any) =>{
            if(item._id == EditId.value){
              item.reason = res.data.data[0].reason
              item.username = res.data.data[0].username
              item.userid = res.data.data[0].userid
            }
          })
        } else {
          ElMessage(res.data.msg)
          editDialogVisible.value = false
        }

      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = false
  editDialogVisible.value = false
}
</script>
